package com.shbaiche.bifenba.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.shbaiche.bifenba.R;


/**
 *实现按给定比例缩放的ImageView
 *@avthor wanghong
 *@time 2018/5/29 16:31
 */

public class AutoScaleImageView extends android.support.v7.widget.AppCompatImageView {
    private Context context;
    private static final String TAG = "AutoScaleImageView";
    private float ratio;//图片宽高比（ = 高 / 宽）


    public AutoScaleImageView(Context context) {
        super(context);
        this.context = context;
        init(null);
    }

    public AutoScaleImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init(attrs);
    }

    public AutoScaleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init(attrs);
    }


    public void init(AttributeSet attrs){
        if(attrs!=null){
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AutoScaleImageView);
            if (typedArray != null){
                for (int i = 0; i < typedArray.getIndexCount(); i++) {
                    int attr = typedArray.getIndex(i);
                    if (attr == R.styleable.AutoScaleImageView_wh_ratio) {
                        ratio = typedArray.getFloat(attr, 1);
                    }
                }

                typedArray.recycle();
            }
        }

        if(ratio > 0){
            doScale();
        }
    }

    private void doScale(){
        int w = getMeasuredWidth();
        if(w >0){
            int h = (int)(w * ratio);
            ViewGroup.LayoutParams ivParams = getLayoutParams();
            ivParams.width = w;
            ivParams.height = h;
            setLayoutParams(ivParams);
            setScaleType(ScaleType.FIT_XY);//避免比例小数误差导致出现白边
            invalidate();
        }else{
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    doScale();
                }
            },100);

        }

    }






}
